use crate::models::user::{RegisterData, User};
use crate::models::response::ResponseResult;
use crate::base::errors::RBlogError;
use crate::utils::auth_util::{generate_user_id, encrypt, decrypt, email_verify};
use rbatis::Rbatis;
use std::collections::HashMap;

use rbatis::rbdc::datetime::FastDateTime;

pub async fn user_register_access(
    rb: &mut Rbatis,
    register_info: RegisterData) -> Result<ResponseResult<HashMap<String, String>>, RBlogError> {
    let encrypt_key: String = std::env::var("KEY").unwrap_or_else(|_| "01234567012345670123456701234567".to_string());
    let register_username = register_info.clone().username;
    let register_email = register_info.clone().email;
    let register_password = register_info.clone().password;
    let email_verify_res = email_verify(rb, &register_email).await;
    if email_verify_res {
        Err(RBlogError::ActixError("email already exit".to_string()))
    } else {
        let user_id = generate_user_id();
        let encrypt_password = encrypt(&encrypt_key, &register_password).unwrap();
        let register_user = User{
            id: Some(user_id.clone()),
            username: Some(register_username.clone()),
            password: Some(encrypt_password.clone()),
            email: Some(register_email.clone()),
            created_at: Some(FastDateTime::now())
        };

        let inserted_res = User::insert(rb, &register_user).await;
        match inserted_res {
            Ok(res) => {
                if res.rows_affected == 0 {
                    Err(RBlogError::DBError("register user error".into()))
                } else {
                    let mut response_user_id:HashMap<String,String> = HashMap::new();
                    response_user_id.insert("id".to_string(), user_id.clone());
                    Ok(
                        ResponseResult::<HashMap<String, String>>::success_with_data(response_user_id)
                    )
                }
            }
            Err(err) => {
                Err(RBlogError::DBError(err.to_string()))
            }
        }
    }
}